package com.imooc.controller;


import com.imooc.pojo.Users;
import com.imooc.pojo.UsersReport;
import com.imooc.pojo.vo.PublisherVideo;
import com.imooc.pojo.vo.UsersVO;
import com.imooc.service.UserService;
import com.imooc.utils.IMoocJSONResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author Zhou
 * @create 2020-11-13 12:16
 */
@RestController
@RequestMapping("/user")
@Api(value = "用户相关业务的接口", tags = {"用户相关业务的controller"})
public class UserController extends BasicController{
    @Autowired
    private UserService userService;

    @Transactional
    @ApiOperation(value = "用户上传头像", notes = "用户上传头像的接口")
    @PostMapping("/uploadFace")
    public IMoocJSONResult uploadFace(String userId, @RequestParam("file") MultipartFile[] files) throws IOException {

        if (StringUtils.isEmpty(userId)){
            return IMoocJSONResult.errorMsg("用户id不能为空");
        }
        //文件保存到的命名空间
        String fileSpace = "D:/programming/imooc_video_dev";

        //保存到数据库中的相对路径
        String uploadPathDB = "/" + userId + "/face";

        //输入输出流
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;

        try {
            if (files != null && files.length > 0){
                String filename = files[0].getOriginalFilename();
                if (! StringUtils.isEmpty(filename)){
                    //文件上传的最终保存路径
                    String finalFacePath = fileSpace + uploadPathDB +"/" +  filename;

                    //设置数据库保存路径
                    uploadPathDB += ("/" + filename);

                    File outFile = new File(finalFacePath);
                    if (outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()){
                        //创建父文件夹
                        outFile.getParentFile().mkdirs();
                    }

                    fileOutputStream = new FileOutputStream(outFile);
                    inputStream = files[0].getInputStream();
                    IOUtils.copy(inputStream, fileOutputStream);
                }
            }else {
                return IMoocJSONResult.errorMsg("上传出错");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return IMoocJSONResult.errorMsg("上传出错");
        } finally {
            if (fileOutputStream != null) {
                //这个方法的作用是把缓冲区的数据强行输出。调用flush是保证缓存清空输出
                fileOutputStream.flush();
                fileOutputStream.close();
            }
            if (inputStream != null){
                inputStream.close();
            }
        }

        //更新DB
        Users user = new Users();
        user.setId(userId);
        user.setFaceImage(uploadPathDB);
        userService.updateUserInfo(user);

        return IMoocJSONResult.ok(uploadPathDB);
    }

    @Transactional
    @ApiOperation(value = "查询用户消息", notes = "查询用户消息接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户Id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "fanId", value = "视频关注者Id", required = true, dataType = "String", paramType = "form")
    })
    @PostMapping("/query")
    public IMoocJSONResult query(String userId, String fanId) throws IOException {
        if (StringUtils.isEmpty(userId)){
            return IMoocJSONResult.errorMsg("用户id不能为空");
        }
        Users users = userService.queryUserById(userId);
        if (users != null){
            UsersVO usersVO = new UsersVO();
            BeanUtils.copyProperties(users, usersVO);

            //设置关注情况
            usersVO.setFollow(userService.queryIfFollow(userId, fanId));
            return IMoocJSONResult.ok(usersVO);
        }else {
            return IMoocJSONResult.errorMsg("用户ID不存在");
        }
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "loginUserId", value = "登录者的主键Id", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "videoId", value = "视频Id", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "publishUserId", value = "视频发布者者Id", required = true, dataType = "String", paramType = "form")
    })
    @ApiOperation(value = "查询视频发布者信息", notes = "查询视频发布者信息的接口")
    @PostMapping("/queryPublisher")
    public IMoocJSONResult queryPublisher(String loginUserId, String videoId, String publishUserId){
        if (StringUtils.isEmpty(publishUserId)){
            return IMoocJSONResult.errorMsg("");
        }

        //1.查询视频发布者信息
        Users users = userService.queryUserById(publishUserId);
        UsersVO publisher = new UsersVO();
        BeanUtils.copyProperties(users, publisher);

        //2.查询当前登录者和视频的点赞关系
        boolean userLikeVideo = userService.isUserLikeVideo(loginUserId, videoId);

        PublisherVideo bean = new PublisherVideo();
        bean.setPublisher(publisher);
        bean.setUserLikeVideo(userLikeVideo);

        return IMoocJSONResult.ok(bean);
    }

    @Transactional
    @ApiOperation(value = "关注用户", notes = "关注用户的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "视频发布者者Id", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "fanId", value = "视频关注者Id", required = true, dataType = "String", paramType = "form")
    })
    @PostMapping("/beYourFans")
    public IMoocJSONResult beYourFans(String userId, String fanId) throws IOException {
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(fanId)){
            return IMoocJSONResult.errorMsg("");
        }

        userService.saveUserFanRelation(userId, fanId);

        return IMoocJSONResult.ok("关注成功");
    }

    @Transactional
    @ApiOperation(value = "取消关注用户", notes = "取消关注用户的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "视频发布者者Id", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "fanId", value = "视频关注者Id", required = true, dataType = "String", paramType = "form")
    })
    @PostMapping("/dontBeYourFans")
    public IMoocJSONResult dontBeYourFans(String userId, String fanId) throws IOException {
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(fanId)){
            return IMoocJSONResult.errorMsg("");
        }

        userService.deleteUserFanRelation(userId, fanId);

        return IMoocJSONResult.ok("取消关注成功");
    }

    @Transactional
    @ApiOperation(value = "用户举报", notes = "用户举报的接口")
    @PostMapping("/reportUser")
    public IMoocJSONResult reportUser(@RequestBody UsersReport usersReport) {

        //保存举报信息
        userService.reportUser(usersReport);
        return IMoocJSONResult.errorMsg("举报成功...有你平台变得更好");
    }


}
